<template>
  <el-row style="padding: 5px">
    <el-row>
        <el-card>
          <el-form :inline="true" :model="paramsSellpro" class="" size="small">
            <el-form-item label="种质名称">
              <el-select v-model="paramsSellpro.germplasmId " placeholder="请选择">
                <el-option
                  v-for="item in germpOptions"
                  :key="item.germplasmId"
                  :label="item.germplasmName"
                  :value="item.germplasmId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="产品名称">
              <el-input v-model="paramsSellpro.sellproName" placeholder="请输入产品名称"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="selectSllproData">搜索</el-button>
              <el-button type="" icon="el-icon-refresh-right" @click="resetForm">重置</el-button>
            </el-form-item>
            <el-form-item style="float: right">
              <el-button type="primary" plain icon="el-icon-plus" @click="addSellproData(1)" v-hasPermi="['agriculture:sellpro:add']">新增</el-button>
              <button_disbable style="margin-right: 10px"></button_disbable>
<!--              <el-button type="warning" plain icon="el-icon-download">导出</el-button>-->
              <el-button type="primary" plain icon="el-icon-sort" @click="changePage">{{this.changeTitle}}</el-button>
            </el-form-item>
          </el-form>
        </el-card>
    </el-row>

    <el-row style="margin-top: 5px" v-show="this.changeON">
      <el-card>
        <el-table :data="tableData.slice((currentPage -1) *pageSize,currentPage*pageSize)" border style="width: 100%">
          <el-table-column align="center" prop="sellproName" label="产品名称" ></el-table-column>
          <el-table-column align="center" prop="sellproImg" label="产品图片" width="180px">
            <template slot-scope="scope">
              <img :src="scope.row.sellproImg" alt="产品图片" style="width: 50px; height: 50px;">
            </template>
          </el-table-column>
          <el-table-column align="center" prop="sellproArea" label="产地"></el-table-column>
          <el-table-column align="center" prop="germplasmId" label="种质">
            <template slot-scope="scope">
              <el-tag effect="dark" type="success">{{scope.row.germplasmName}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="sellproWeight" label="产品重量"></el-table-column>
          <el-table-column align="center" prop="sellproGuige" label="产品规格"></el-table-column>
          <el-table-column align="center" prop="" label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-c-scale-to-original" class="mini_Button" @click="goToVersionPage">溯源版本</el-button>
              <el-button type="warning" icon="el-icon-edit" class="mini_Button" @click="updataSellproData(scope.row,1)" v-hasPermi="['agriculture:sellpro:edit']">修改</el-button>
              <el-button type="danger" icon="el-icon-delete" class="mini_Button" @click="deleteSellproData(scope.row.sellproId)" v-hasPermi="['agriculture:sellpro:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          style="margin: 20px 0; float: right"
          :current-page.sync="currentPage"
           background
          :page-size="pageSize"
           layout="total, prev, pager, next, jumper"
          :total="this.tableData.length">
        </el-pagination>
      </el-card>
    </el-row>
    <!--切换页面-->
    <el-row :gutter="10" v-show="this.changeOFF">
      <el-col v-for="(item, index) in tableData" :key="index" :span="6" style="margin-top: 5px">
        <el-card style="margin-bottom: 5px">
          <el-row>
            <el-col :span="12">
              <div><i style="font-size: 23px;font-weight: 800">{{ item.sellproName }}</i></div>
              <span style="font-size: 13px">{{ item.remark }}</span>
            </el-col>
            <el-col :span="12">
              <img :src="item.sellproImg" style="width: 75px;height: 75px;float: right">
            </el-col>
          </el-row>
          <el-row class="el_bottom"><span>产地</span><span class="el_span">{{item.sellproArea}}</span></el-row>
          <el-row class="el_bottom"><span>产品重量</span><span class="el_span">{{ item.sellproWeight }}</span></el-row>
          <el-row class="el_bottom"><span>产品规格</span><span class="el_span">{{ item.sellproGuige }}</span></el-row>
          <el-row style="margin-top: 10px;text-align: center">
            <el-button-group>
              <el-button type="primary" icon="el-icon-c-scale-to-original" class="mini_Button2" @click="goToVersionPage">溯源版本</el-button>
              <el-button type="warning" icon="el-icon-edit" class="mini_Button2" @click="updataSellproData(item,1)" v-hasPermi="['agriculture:sellpro:edit']">修改</el-button>
              <el-button type="danger" icon="el-icon-delete" class="mini_Button2" @click="deleteSellproData(item.sellproId)" v-hasPermi="['agriculture:sellpro:remove']">删除</el-button>
            </el-button-group>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <el-drawer
      :visible.sync="drawer"
       direction="rtl"
       size="40%">
      <template v-slot:title>
        <div style="color: black;font-weight:1000; font-size: 20px;">{{drawerTitle}}</div>
      </template>
      <el-row style="padding: 0 20px 20px 20px">
        <el-row>
          <el-form :inline="true" :model="addData" class="demo-form-inline">
            <el-form-item>
              <template v-slot:label>
                <i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>
                产品名称
              </template>
              <el-input v-model="addData.sellproName" placeholder="请输入产品名称" class="input_weight"></el-input>
            </el-form-item>
            <el-form-item label="生长地块" style="float: right">
              <el-select v-model="addData.landId" placeholder="请选择生长地块"  class="input_weight">
                <el-option v-for="item in landOPtions"
                :key="item.landId"
                :value="item.landId"
                :label="item.landName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-row>

        <el-row>
          <el-form :inline="true" :model="addData" class="demo-form-inline">
            <el-form-item>
              <template v-slot:label>
                <i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>
                产品产地
              </template>
              <el-input v-model="addData.sellproArea" placeholder="请输入产品产地" class="input_weight"></el-input>
            </el-form-item>
            <el-form-item label="环境设备" style="float: right">
              <el-select v-model="addData.deviceId" placeholder="请选择环境设备"  class="input_weight">
                <el-option label="设备1" value="设备1"></el-option>
                <el-option label="设备2" value="设备2"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-row>

        <el-row>
            <el-form :inline="true" :model="addData" class="demo-form-inline">
              <el-form-item>
                <template v-slot:label>
                  <i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>
                  产品重量
                </template>
                <el-input v-model="addData.sellproWeight" placeholder="请输入产品重量" class="input_weight"></el-input>
              </el-form-item>
              <el-form-item label="监控设备" style="float: right">
                <el-select v-model="addData.cameraId" placeholder="请选择监控设备"  class="input_weight">
                  <el-option label="设备1" value="设备1"></el-option>
                  <el-option label="设备2" value="设备2"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-row>

        <el-row>
            <el-form :inline="true" :model="addData" class="demo-form-inline">
              <el-form-item>
                <template v-slot:label>
                  <i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>
                  产品规格
                </template>
                <el-input v-model="addData.sellproGuige" placeholder="请输入产品规格" class="input_weight"></el-input>
              </el-form-item>
              <el-form-item label="业务人员" style="float: right">
                <el-select v-model="addData.staffId" placeholder="请选择业务人员"  class="input_weight">
                  <el-option v-for="item in staffOptions"
                    :key="item.staffId"
                    :value="item.staffId"
                    :label="item.staffName">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-row>

        <el-row>
            <el-form :inline="true" :model="addData" class="demo-form-inline">
              <el-form-item label="种植种质" style="margin-left: 15px">
                <el-select v-model="addData.germplasmId" placeholder="请选择" class="input_weight" filterable="false" allow-create>
                  <el-option
                    v-for="item in germpOptions"
                    :key="item.germplasmId"
                    :label="item.germplasmName"
                    :value="item.germplasmId">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="宣传店铺" style="float: right">
                <el-select v-model="addData.shopId" placeholder="请选择宣传店铺"  class="input_weight">
                  <el-option v-for="item in stopOptions"
                  :key="item.shopId"
                  :value="item.shopId"
                  :label="item.shopName"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-row>

        <el-row>
            <el-form :inline="true" :model="addData" class="demo-form-inline">
              <el-form-item label="生产批次" style="margin-left: 15px">
                <el-select v-model="addData.batchId" placeholder="请选择生产批次"  class="input_weight">
                  <el-option v-for="item in batchOptions"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item style="float: right">
                <template v-slot:label>
                  <i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>
                  溯源页面
                </template>
                <el-select v-model="addData.h5Url" placeholder="请选择溯源"  class="input_weight">
                  <el-option label="页面一" value="1"></el-option>
                  <el-option label="页面二" value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-row>

        <el-row>
            <el-form :inline="true" :model="addData" class="demo-form-inline" style="margin-top: 10px">
              <el-form-item >
                <template v-slot:label>
                  <i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>
                  产品介绍
                </template>
                <el-input   type="textarea" :rows="3"v-model="addData.remark" placeholder="请输入产品介绍" style="width: 400px;margin-left: 10px"></el-input>
              </el-form-item>
            </el-form>
        </el-row>
          <el-form :inline="true" :model="addData" class="demo-form-inline" style="margin-top: 10px">
            <el-form-item>
              <template v-slot:label>
                <i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>
                产品图片
              </template>
              <el-upload
                ref="upload"
                action="http://117.141.22.134:18080/uploadFile/"
                :auto-upload="false"
                list-type="picture-card"
                :limit="1"
                :on-success="handleUploadSuccess"
                :on-change="handleChange"
                :on-remove="handleRemove"
                 style="margin-left: 10px">
                <i :class=" uploadStatus == true ? 'el-icon-close' :'el-icon-plus'"></i>
              </el-upload>
              <span style="font-size: 14px;color: #cccccc">注:图片像素最好改成200px乘200px再上传</span>
            </el-form-item>
          </el-form>
      </el-row>
      <div style="position: absolute; bottom: 20px; right: 20px;">
        <el-button  @click="drawer=false">取消</el-button>
        <el-button type="primary"  @click="handleButtonClick">确定</el-button>
      </div>
    </el-drawer>
  </el-row>
</template>
<script>
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Template from "@/views/iot/template/index.vue";
import {addSellpro, listSellpro,delSellpro,updateSellpro} from "@/api/agriculture/sellpro";
import Button_disbable from "@/views/agriculture/buttonDis/button_disbable.vue";
import {listStaff} from "@/api/agriculture/staff";
import {listGermplasm} from "@/api/agriculture/germplasm";
import {listShop} from "@/api/agriculture/shop";
import {listTBatch} from "@/api/agriculture/tbatch";
import {listLand} from "@/api/agriculture/land";
export default {
  components: {Button_disbable, Template},
  data() {
    const initialAddData={
      sellproName:'',
      sellproArea:'',
      sellproWeight:'',
      sellproGuige:'',
      sellproImg:'',
      germplasmId:'',
      batchId:'',
      landId:'',
      deviceId:'',
      cameraId:'',
      staffId:'',
      shopId:'',
      h5Url:'',
      remark:'',
      status:'',
      orderNum:'',
      // createBy:'',
      // createTime:'',
      // updateBy:'',
      // updateTime:'',
      delFlag:'',};
    return {
      currentPage:1,
      pageSize:10,
      uploadStatus:false,
      addOrUpdate:0,
      changeON:false,
      changeOFF:true,
      changeTitle:'表格模式',
      drawerTitle:'',
      changeCount:1,
      drawer:false,
      addDataError:'',
      tableData: [],
      addData: { ...initialAddData },
      initialAddData,
      optionData:[],
      paramsSellpro:{
        sellproName:'',
        sellproArea:'',
        sellproWeight:'',
        sellproGuige:'',
        sellproImg:'',
        germplasmId:'',
        batchId:'',
        landId:'',
        deviceId:'',
        cameraId:'',
        staffId:'',
        shopId:'',
        h5Url:'',
        status:'',
        orderNum:'',
      },
      staffOptions:'',
      batchOptions:'',
      germpOptions:'',
      stopOptions:'',
      landOPtions:'',
      requiredFields :
        {sellproName: '请填写完整产品名称！', sellproArea: '请填写完整产品产地！', sellproWeight: '请填写完整产品重量！',
        sellproGuige: '请填写完整产品规格！', remark: '请填写完整产品介绍！', h5Url: '请选择溯源页面！'}
    }
  },
  async  mounted() {
  await this.getSellproData()
  await this.getOptionData()
    },
  methods:{
    async getOptionAllData()
    {
      const row1 = await listStaff(); this.staffOptions = row1.rows
      const row2 = await listShop() ; this.stopOptions = row2.rows
      const row3 = await  listLand(); this.landOPtions = row3.rows
      const row4 = await listTBatch();
      this.batchOptions = row4.rows.map(item =>{
          const findData = this.germpOptions.find(item1 =>item.germplasmId === item1.germplasmId)
          const findData2 = row4.rows.find(item2 => item.landId === item2.landId)
        return{
            value:item.batchId,
            label:item.batchCode+'('+findData.germplasmName+')',
            landId:item.landId,
            landName:findData2.landName

        }
      })
    },
    // 抽屉确定按钮选择监听修改或新增
    handleButtonClick() {
      if (this.addOrUpdate === 1) {
        this.updataSellproData(this.addData, 2);
      } else {
        this.addSellproData(2);
      }
    },
    // 警告消息
    openMessage(type,mes) {
      this.$notify({
        title: '提示',
        message: mes,
        offset: 30,
        type: type
      });
    },
    async getOptionData()
    {
      const row = await listSellpro(this.paramsSellpro);
      this.optionData = [...new Set(row.rows.map(item => item.germplasmId))].map(germplasmId => {
        return {value: germplasmId, label: germplasmId};
      });
    },
    // 监听添加图片的动态
    handleRemove(file, fileList) {
      this.uploadStatus=false
    },
    // 监听添加图片的动态
    handleChange(file, fileList) {
      if (file.status === 'ready') {
        this.uploadStatus=true
      };
    },
   async handleUploadSuccess(response, file, fileList) {
      if (response.data.path) {
        const imagePath = response.data.path;
        this.addData.sellproImg = imagePath;
        try {
         await addSellpro(this.addData);
        } catch (error) {
          console.error('Error occurred while adding sellpro:', error);
          this.addDataError=1
        }
      }
    },
    // 修改产品
    async updataSellproData(row,buttonId){
      if(buttonId == 1) {this.addData = {...row} ;this.drawerTitle ='修改溯源产品';this.drawer=true;this.addOrUpdate = 1;this.getOptionAllData() }
      else if(buttonId == 2){
        for (let field of Object.keys(this.requiredFields)) {
          if (!this.addData[field]) {
            this.openMessage('warning', this.requiredFields[field]);
            return;
          }
        }
       try {
         await updateSellpro(this.addData)
         this.openMessage('success', '修改成功！');
         await this.getSellproData()
         this.drawer = false
       }catch (error){
         console.error('Error occurred while update sellpro:', error);
         this.openMessage('error', '修改失败！');
       }
      }
    },
    // 添加产品
    async addSellproData(buttonId) {
      if(buttonId == 1) {this.addData = { ...this.initialAddData };this.drawerTitle ='添加溯源产品';this.drawer = true; this.addOrUpdate = 0;this.getOptionAllData()}
      else if(buttonId == 2){
        for (let field of Object.keys(this.requiredFields)) {
          if (!this.addData[field]) {
            this.openMessage('warning', this.requiredFields[field]);
            return;
          }
        }
        if(!this.uploadStatus){
          this.openMessage('warning', '请选择图片！');
          return;
        }
        await this.$refs.upload.submit();
        if(!this.addDataError)
        {
          this.openMessage('success', '添加成功！');
          this.drawer = false
         await  this.getSellproData();
        } else {
          this.openMessage('error', '添加失败！');}
      }
    },
    // 获取产品
   async getSellproData()
    {
      const  row = await listSellpro(this.paramsSellpro)
      const  row1 = await listGermplasm()
      this.germpOptions = row1.rows
      this.tableData = row.rows.map(item1=>{
        const findData =row1.rows.find(item2 => item1.germplasmId == item2.germplasmId)
        return {
          ...item1,
          germplasmName:findData.germplasmName
        }
      })
    },
    // 查询产品
    async selectSllproData()
    {
      this.getSellproData()
    },
    // 删除产品
    async deleteSellproData(id)
    {
      this.$confirm('确认删除？')
        .then(async _ => {
         try{
           delSellpro(id)
           this.openMessage('success', '删除成功！');
           await this.getSellproData()
         }catch (error){
           console.log("溯源产品删除错误:",error)
           this.openMessage('error', '删除失败！');
         }
        }).catch(_ => {
          return
        });
    },
    // 重置
    resetForm()
    {
        this.paramsSellpro.sellproName='',
        this.paramsSellpro.germplasmId=''
        this.getSellproData()
    },
    // 切换模式
    changePage() {
      this.changeON = this.changeCount == 1;
      this.changeOFF = this.changeCount !== 1;
      this.changeCount = this.changeCount === 1 ? 0 : 1;
      this.changeTitle = this.changeTitle === '表格模式' ? '卡片模式' :'表格模式';
    },
    // 跳转页面
    goToVersionPage()
    {
      this.$router.push('/trace/version');
    },
  }
}
</script>
<style scoped>
.mini_Button{
  font-size:11px;
  padding: 4px 9px
}
.mini_Button2{
  font-size:12px;
  padding: 5px 9px;
}
.el_span{
  float: right;
}
.el_bottom{
  font-size: 14px;
  margin-top: 10px;
  border-bottom: 1px solid ;
  border-color: rgba(0,0,0,0.1);
  padding-bottom: 10px;
}
.input_weight{
  width: 165px;
  margin-left: 10px;
}
</style>
